package com.netty.learn.server;


import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * @Author: JohnCoding
 * @Description:
 * @date: 2020/8/21 22:13
 */
public class ClientHandler {
    private Socket client;

    private int MAX_DATA_LEN = 1024;

    ClientHandler( Socket client){
        this.client = client;
    }

    public void start(){
        System.out.println("有新的客户端连接");
        new Thread(new Runnable() {
            @Override
            public void run() {
                doStart();
            }
        }).start();
    }

    private void doStart(){
        try {
            InputStream inputStream = client.getInputStream();
            while (true){
                byte[] data = new byte[MAX_DATA_LEN];
                int len;
                while ((len = inputStream.read(data)) != -1){
                    String message = new String(data);
                    System.out.println("收到客户端信息："+ message.toString());
                    client.getOutputStream().write(data);
                }
                TimeUnit.SECONDS.sleep(5);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
